/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Project: javase - ObjectStream2
 * <p>Powered by webrx On 2021-12-15 19:13:20
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class ObjectStream2 {

    public static void main(String[] args) {
        try (var oop = new ObjectInputStream(new FileInputStream("d:/user.db"))) {
            List<User> a = (List<User>) oop.readObject();
            System.out.println(a.size());
            a.forEach(System.out::println);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void read(String[] args) {
        try (var oop = new ObjectInputStream(new FileInputStream("d:/user.db"))) {
            User a = (User) oop.readObject();
            System.out.println(a.getName());
            System.out.println(a);

            User b = (User) oop.readObject();
            System.out.println(b.getName());
            System.out.println(b);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    public static void write(String[] args) {
        var lisi = new User();
        lisi.setId(10);
        lisi.setName("李四");
        lisi.setSex("男");
        lisi.setMoney(1000D);
        lisi.setBirth(LocalDate.of(1985, 10, 13));

        var wu = new User();
        wu.setId(22);
        wu.setName("王五");
        wu.setSex("女");
        wu.setMoney(3.0D);
        wu.setBirth(LocalDate.now());

        List<User> data = new ArrayList<>();
        data.add(lisi);
        data.add(wu);

        try (var oop = new ObjectOutputStream(new FileOutputStream("d:/user.db"))) {
            oop.writeObject(data);
            //oop.writeObject(wu);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
